// src/views/forum/Forum.vue
<template>
  <div class="forum-container">
    <!-- 发帖表单 -->
    <el-form :model="postForm" label-width="80px" @submit.native.prevent>
      <el-form-item label="标题">
        <el-input v-model="postForm.title" placeholder="请输入标题" clearable></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input type="textarea" v-model="postForm.content" placeholder="请输入内容" rows="4"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createPost" :loading="postLoading">发帖</el-button>
      </el-form-item>
    </el-form>

    <!-- 帖子列表 -->
    <el-table :data="postList" style="width: 100%" v-loading="postListLoading">
      <el-table-column prop="title" label="标题" width="200"></el-table-column>
      <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userId" label="发帖人" width="120"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deletePost(scope.row.id)"
            :disabled="!canDelete(scope.row.userId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 帖子分页 -->
    <pagination
      v-show="postTotal > 0"
      :total="postTotal"
      :page.sync="postPageIndex"
      :limit.sync="postPageSize"
      @pagination="getPostPage"
    />

    <!-- 回帖表单 -->
    <el-form :model="replyForm" label-width="80px" @submit.native.prevent class="reply-form">
      <el-form-item label="帖子ID">
        <el-input v-model="replyForm.postId" placeholder="请输入帖子ID" clearable></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input type="textarea" v-model="replyForm.content" placeholder="请输入内容" rows="3"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createReply" :loading="replyLoading">回帖</el-button>
      </el-form-item>
    </el-form>

    <!-- 回帖列表 -->
    <el-table :data="replyList" style="width: 100%" v-loading="replyListLoading">
      <el-table-column prop="postId" label="帖子ID" width="120"></el-table-column>
      <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userId" label="回帖人" width="120"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deleteReply(scope.row.id)"
            :disabled="!canDelete(scope.row.userId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 回帖分页 -->
    <pagination
      v-show="replyTotal > 0"
      :total="replyTotal"
      :page.sync="replyPageIndex"
      :limit.sync="replyPageSize"
      @pagination="getReplyPage"
    />
  </div>
</template>

<script>
import forumApi from '@/api/forum'
import Pagination from '@/components/Pagination'
import { mapState } from 'vuex'

export default {
  name: 'Forum',
  components: { Pagination },
  data () {
    return {
      postForm: {
        title: '',
        content: '',
        userId: ''
      },
      replyForm: {
        postId: '',
        content: '',
        userId: ''
      },
      postList: [],
      postTotal: 0,
      postPageIndex: 1,
      postPageSize: 10,
      replyList: [],
      replyTotal: 0,
      replyPageIndex: 1,
      replyPageSize: 10,
      postLoading: false,
      replyLoading: false,
      postListLoading: false,
      replyListLoading: false
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created () {
    this.checkUserProfile()
  },
  methods: {
    // 检查用户是否登录并初始化数据
    checkUserProfile () {
      if (!this.userInfo || !this.userInfo.id) {
        this.$message.error('请先登录')
        this.$router.push('/login')
        return
      }
      this.postForm.userId = this.userInfo.id
      this.replyForm.userId = this.userInfo.id
      this.getPostPage()
      this.getReplyPage()
    },
    // 判断是否可以删除（仅限本人或管理员）
    canDelete (userId) {
      return this.userInfo.id === userId || this.userInfo.role === 'admin'
    },
    // 创建帖子
    createPost () {
      if (!this.postForm.title || !this.postForm.content) {
        this.$message.error('标题和内容不能为空')
        return
      }
      this.postLoading = true
      forumApi.createPost(this.postForm).then(res => {
        if (res.code === 1) {
          this.$message.success('发帖成功')
          this.postForm.title = ''
          this.postForm.content = ''
          this.getPostPage()
        } else {
          this.$message.error(res.message || '发帖失败')
        }
      }).catch(() => {
        this.$message.error('发帖失败')
      }).finally(() => {
        this.postLoading = false
      })
    },
    // 删除帖子
    deletePost (id) {
      this.$confirm('确定删除此帖子吗？', '提示', {
        type: 'warning'
      }).then(() => {
        forumApi.deletePost(id, this.userInfo.id, this.userInfo.role).then(res => {
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getPostPage()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    },
    // 创建回帖
    createReply () {
      if (!this.replyForm.postId || !this.replyForm.content) {
        this.$message.error('帖子ID和内容不能为空')
        return
      }
      this.replyLoading = true
      forumApi.createReply(this.replyForm).then(res => {
        if (res.code === 1) {
          this.$message.success('回帖成功')
          this.replyForm.content = ''
          this.getReplyPage()
        } else {
          this.$message.error(res.message || '回帖失败')
        }
      }).catch(() => {
        this.$message.error('回帖失败')
      }).finally(() => {
        this.replyLoading = false
      })
    },
    // 删除回帖
    deleteReply (id) {
      this.$confirm('确定删除此回帖吗？', '提示', {
        type: 'warning'
      }).then(() => {
        forumApi.deleteReply(id, this.userInfo.id, this.userInfo.role).then(res => {
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getReplyPage()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    },
    // 获取帖子分页列表
    getPostPage () {
      this.postListLoading = true
      const data = {
        pageIndex: this.postPageIndex,
        pageSize: this.postPageSize
      }
      forumApi.getPostPage(data).then(res => {
        if (res.code === 1) {
          this.postList = res.response.list
          this.postTotal = res.response.total
        } else {
          this.$message.error(res.message || '获取帖子列表失败')
        }
      }).catch(() => {
        this.$message.error('获取帖子列表失败')
      }).finally(() => {
        this.postListLoading = false
      })
    },
    // 获取回帖分页列表
    getReplyPage () {
      if (!this.replyForm.postId) return
      this.replyListLoading = true
      const data = {
        postId: this.replyForm.postId,
        pageIndex: this.replyPageIndex,
        pageSize: this.replyPageSize
      }
      forumApi.getReplyPage(data).then(res => {
        if (res.code === 1) {
          this.replyList = res.response.list
          this.replyTotal = res.response.total
        } else {
          this.$message.error(res.message || '获取回帖列表失败')
        }
      }).catch(() => {
        this.$message.error('获取回帖列表失败')
      }).finally(() => {
        this.replyListLoading = false
      })
    }
  }
}
</script>

<style scoped>
.forum-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.reply-form {
  margin-top: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>
